package com.richie696.bank.account.controller;

import com.richie696.bank.account.model.AccountRequestModel;
import com.richie696.bank.account.model.AccountResponseModel;
import com.richie696.bank.account.service.AccountService;
import com.richie696.bank.json.ExecuteResult;
import com.richie696.bank.system.AbstractServlet;
import com.richie696.bank.utils.WebUtils;
import spring.annotations.Autowired;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@WebServlet(name = "transfer", urlPatterns = "/service/transfer")
public class AccountServlet extends AbstractServlet {

    @Autowired
    private AccountService accountService;
    private AccountRequestModel model;

    public AccountServlet() {
        accountService = webApplicationContext.getBean("accountService");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        ExecuteResult<AccountRequestModel> param = parseParameter(request);
        if (!param.isSuccess()) {
            WebUtils.sendJsonResult(response, param);
            return;
        }
        // 执行转账业务
        ExecuteResult<AccountResponseModel> result = accountService.doTransferProcess(model);
        // 返回结果给页面
        WebUtils.sendJsonResult(response, result);
    }

    private ExecuteResult<AccountRequestModel> parseParameter(HttpServletRequest request) {
        AccountRequestModel model = new AccountRequestModel();
        Optional.ofNullable(request.getParameter("fromCardNo")).ifPresent(model::setFromCardNo);
        Optional.ofNullable(request.getParameter("toCardNo")).ifPresent(model::setToCardNo);
        Optional.ofNullable(request.getParameter("money")).ifPresent(model::setMoney);
        if (model.isInvalid()) {
            return ExecuteResult.getErrorResult("转账请求无效");
        }
        setModel(model);
        return ExecuteResult.getSuccess(model);
    }

    public void setModel(AccountRequestModel model) {
        this.model = model;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}
